package smedi.ismedi.web.bff.controller.safetycheck;

import com.smedi.ismedi.file.dto.response.FileInfoResponse;
import com.smedi.ismedi.file.feign.RemoteFileFeignApi;
import com.smedi.ismedi.safetycheck.dto.request.danger.*;
import com.smedi.ismedi.safetycheck.dto.response.PaginationResponse;
import com.smedi.ismedi.safetycheck.dto.response.danger.*;
import com.smedi.ismedi.safetycheck.feign.RemoteHiddenDangerFeignApi;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import smedi.ismedi.web.bff.controller.BaseController;
import smedi.ismedi.web.bff.dto.HiddenDangerOperateDetailResponse;
import smedi.ismedi.web.bff.dto.HiddenDangerOperateResponse;
import smedi.ismedi.web.bff.infrastructure.util.FileHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Jimmy
 * @Date 2021/6/16 17:56
 */
@Api(tags = {"安全隐患接口"})
@RequestMapping(value = "/webbff/v1")
@RestController
@RequiredArgsConstructor
public class HiddenDangerController extends BaseController {
    private final RemoteHiddenDangerFeignApi remoteHiddenDangerFeignApi;
    private final RemoteFileFeignApi fileFeignApi;

    private final DozerUtil dozerUtil;

    @Value("${fdfs.service.address.in}")
    private String FDFS_SERVICE_ADDRESS_IN;

    @Value("${fdfs.service.address.out}")
    private String FDFS_SERVICE_ADDRESS_OUT;

    @ApiOperation(value = "安全隐患维护", nickname = "安全隐患维护")
    @PostMapping(value = "/hiddenDanger")
    ResponseData<HiddenDangerResponse> hiddenDanger(@RequestBody HiddenDangerRequest hiddenDangerRequest) {
        ResponseData<HiddenDangerResponse> responseData;
        if (hiddenDangerRequest.getId() != null) {
            responseData = remoteHiddenDangerFeignApi.editHiddenDanger(hiddenDangerRequest);
        } else {
            responseData = remoteHiddenDangerFeignApi.addHiddenDanger(hiddenDangerRequest);
        }
        return responseData;
    }

    @ApiOperation(value = "安全隐患批量提交", nickname = "安全隐患批量提交")
    @PostMapping(value = "/batchAddHiddenDanger")
    ResponseData<List<HiddenDangerResponse>> batchAddHiddenDanger(@RequestBody List<HiddenDangerRequest> hiddenDangerRequestList) {
        return remoteHiddenDangerFeignApi.batchAddHiddenDanger(hiddenDangerRequestList);
    }

    @ApiOperation(value = "隐患删除", nickname = "隐患删除")
    @DeleteMapping(value = "/hiddenDanger/deleteHiddenDanger")
    ResponseData<Boolean> deleteHiddenDanger(@RequestParam("hiddenDangerIds") List<Long> ids) {
        return remoteHiddenDangerFeignApi.deleteHiddenDangerById(ids);
    }


    /**
     * 隐患整改
     *
     * @param hiddenDangerRectificationRequest
     * @return
     */
    @ApiOperation(value = "隐患整改", nickname = "隐患整改")
    @PostMapping(value = "/hiddenDanger/hiddenDangerRectification")
    ResponseData<HiddenDangerRectificationResponse> hiddenDangerRectification(@Validated @ApiParam(value = "param", required = true) @RequestBody HiddenDangerRectificationRequest hiddenDangerRectificationRequest) {
        return remoteHiddenDangerFeignApi.hiddenDangerRectification(hiddenDangerRectificationRequest);
    }

    /**
     * 隐患复查
     *
     * @param hiddenDangerReviewRequest
     * @return
     */
    @ApiOperation(value = "隐患复查", nickname = "隐患复查")
    @PostMapping(value = "/hiddenDanger/hiddenDangerReview")
    ResponseData<HiddenDangerReviewResponse> hiddenDangerReview(@Validated @ApiParam(value = "param", required = true) @RequestBody HiddenDangerReviewRequest hiddenDangerReviewRequest) {
        return remoteHiddenDangerFeignApi.hiddenDangerReview(hiddenDangerReviewRequest);
    }

    /**
     * 隐患移交
     *
     * @param hiddenDangerChangeRectificationPersonRequest
     * @return
     */
    @ApiOperation(value = "隐患移交", nickname = "隐患移交")
    @PostMapping(value = "/hiddenDanger/hiddenDangerChangeRectificationPerson")
    ResponseData<HiddenDangerChangeRectificationPersonResponse> hiddenDangerChangeRectificationPerson(@Validated @ApiParam(value = "param", required = true) @RequestBody HiddenDangerChangeRectificationPersonRequest hiddenDangerChangeRectificationPersonRequest) {
        return remoteHiddenDangerFeignApi.hiddenDangerChangeRectificationPerson(hiddenDangerChangeRectificationPersonRequest);
    }

    /**
     * 隐患关闭
     *
     * @param hiddenDangerCloseRequest
     * @return
     */
    @ApiOperation(value = "隐患关闭", nickname = "隐患关闭")
    @PostMapping(value = "/hiddenDanger/hiddenDangerClose")
    ResponseData<Boolean> hiddenDangerClose(@Validated @ApiParam(value = "param", required = true) @RequestBody HiddenDangerCloseRequest hiddenDangerCloseRequest) {
        return remoteHiddenDangerFeignApi.hiddenDangerClose(hiddenDangerCloseRequest);
    }

    /**
     * web端安全隐患查询
     *
     * @param webSearchHiddenDangerRequest
     * @return
     */
    @ApiOperation(value = "web端安全隐患查询", nickname = "web端安全隐患查询")
    @GetMapping(value = "/hiddenDangerQuery/webSearchHiddenDanger")
    ResponseData<PaginationResponse<HiddenDangerResponse>> webSearchHiddenDanger(@Validated @SpringQueryMap WebSearchHiddenDangerRequest webSearchHiddenDangerRequest) {
        return remoteHiddenDangerFeignApi.webSearchHiddenDanger(webSearchHiddenDangerRequest);
    }

    /**
     * 安全隐患详情查询
     *
     * @param hiddenDangerId
     * @return
     */
    @ApiOperation(value = "安全隐患详情查询", nickname = "安全隐患详情查询")
    @GetMapping(value = "/hiddenDangerQuery/searchHiddenDangerDetail")
    ResponseData<HiddenDangerOperateDetailResponse> searchHiddenDangerDetail(@ApiParam(value = "hiddenDangerId", required = true) @RequestParam(value = "hiddenDangerId", required = true) Long hiddenDangerId) {
        ResponseData<HiddenDangerDetailResponse> responseResponseData = remoteHiddenDangerFeignApi.searchHiddenDangerDetail(hiddenDangerId);

        HiddenDangerDetailResponse response = responseResponseData.getData();
        HiddenDangerOperateDetailResponse hiddenDangerOperateDetailResponse = dozerUtil.convertor(response, HiddenDangerOperateDetailResponse.class);

        Map<String, Map<String, Object>> detailInfo = response.getDetailInfo();
        List<HiddenDangerOperateResponse> hiddenDangerOperateResponses = new ArrayList<>();
        for (String date : detailInfo.keySet()) {
            HiddenDangerOperateResponse operateResponse = new HiddenDangerOperateResponse();
            if (date.contains(" ")) {
                operateResponse.setOperateTime(LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            } else {
                operateResponse.setOperateTime(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
            }
            Map<String, Object> objectMap = detailInfo.get(date);
            for (String name : objectMap.keySet()) {
                operateResponse.setOperateName(name);
                operateResponse.setOperateInfo(objectMap.get(name));
            }
            hiddenDangerOperateResponses.add(operateResponse);
        }

        List<HiddenDangerOperateResponse> hiddenDangerOperateResponsesSort = hiddenDangerOperateResponses.stream().sorted(Comparator.comparing(HiddenDangerOperateResponse::getOperateTime)).collect(Collectors.toList());

        hiddenDangerOperateDetailResponse.setOperateResponses(hiddenDangerOperateResponsesSort);
        return new ResponseData<>().success(hiddenDangerOperateDetailResponse);
    }

    /**
     * 查询隐患库数据
     *
     * @param firstLevelDirectory
     * @return
     */
    @ApiOperation(value = "查询隐患库数据", nickname = "查询隐患库数据")
    @GetMapping(value = "/hiddenDangerStoreHouse/getHiddenDangerStoreHouse")
    ResponseData<List<NodeResponse<HiddenDangerStoreHouseDetailResponse>>> getHiddenDangerStoreHouse(@ApiParam(value = "firstLevelDirectory") @RequestParam(value = "firstLevelDirectory", required = false) String firstLevelDirectory,
                                                                                 @ApiParam(value = "secondLevelDirectory") @RequestParam(value = "secondLevelDirectory", required = false) String secondLevelDirectory,
                                                                                 @ApiParam(value = "thirdLevelDirectory") @RequestParam(value = "thirdLevelDirectory", required = false) String thirdLevelDirectory,
                                                                                 @ApiParam(value = "content") @RequestParam(value = "content", required = false) String content) throws InstantiationException, IllegalAccessException {
        return remoteHiddenDangerFeignApi.getHiddenDangerStoreHouse(firstLevelDirectory, secondLevelDirectory, thirdLevelDirectory, content);
    }

    /**
     * 查询隐患库一级目录
     */
    @ApiOperation(value = "查询隐患库一级目录", nickname = "查询隐患库一级目录")
    @GetMapping(value = "/hiddenDangerStoreHouse/getFirstLevelDirectory")
    ResponseData<List<String>> getFirstLevelDirectory() {
        return remoteHiddenDangerFeignApi.getFirstLevelDirectory();
    }

    @ApiOperation(httpMethod = "POST", value = "预览多个隐患记录")
    @PostMapping(value = "/previewHiddenDangerBatch")
    public ResponseData<String> previewHiddenDangerBatch(@Validated @RequestBody WebSearchHiddenDangerRequest webSearchHiddenDangerRequest, HttpServletResponse response) throws IOException {
        String signKey = remoteHiddenDangerFeignApi.exportHiddenDangerBatch(webSearchHiddenDangerRequest).getData();
        FileInfoResponse fileInfoResponse = fileFeignApi.getFileInfo(signKey).getData();
        String url = FileHelper.getUrl(FDFS_SERVICE_ADDRESS_OUT, fileInfoResponse.getStorageGroup(), fileInfoResponse.getPath(), fileInfoResponse.getName(), response);

        return new ResponseData<>().success(url);
    }

    @ApiOperation(httpMethod = "POST", value = "导出多个隐患记录")
    @PostMapping(value = "/exportHiddenDangerBatch")
    public ResponseData<Boolean> exportHiddenDangerBatch(@Validated @RequestBody WebSearchHiddenDangerRequest webSearchHiddenDangerRequest, HttpServletResponse response) throws IOException {
        String signKey = remoteHiddenDangerFeignApi.exportHiddenDangerBatch(webSearchHiddenDangerRequest).getData();
        FileInfoResponse fileInfoResponse = fileFeignApi.getFileInfo(signKey).getData();
        FileHelper.downloadFile(FDFS_SERVICE_ADDRESS_IN, fileInfoResponse.getStorageGroup(), fileInfoResponse.getPath(), fileInfoResponse.getName(), response);

        return new ResponseData<>().success(true);
    }
}
